﻿/*

The MIT License

Copyright (c) 2010 Cartesian Analytics, Inc. 

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace Pipra.Math.Geometry
{
    /// <summary>
    /// A collection of points.
    /// </summary>
    public class MultiPoint2 :
        Collection<Point2>,
        IPlanarGeometry<double>,
        IEquatable<MultiPoint2>,
        IIntersectable<Point2>,
        IHasDistance<double,Point2>,
        IContainable<Mbr>,
        ICloneable,
        ISelfIntersectable
    {

        public static bool operator ==(MultiPoint2 a, MultiPoint2 b)
        {
            return ReferenceEquals(a, b) || (!ReferenceEquals(null, a) && a.Equals(b));
        }

        public static bool operator !=(MultiPoint2 a, MultiPoint2 b)
        {
            return !ReferenceEquals(a, b) && (ReferenceEquals(null, a) || !a.Equals(b));
        }

        /// <summary>
        /// Constructs a new empty multi point.
        /// </summary>
        public MultiPoint2() { }
        /// <summary>
        /// Constructs a new empty multi point expecting the given number of points.
        /// </summary>
        /// <param name="expectedCapacity">The expected number of points.</param>
        public MultiPoint2(int expectedCapacity)
            : base(new List<Point2>(expectedCapacity)) { }
        /// <summary>
        /// Constructs a new multi point containing the given points.
        /// </summary>
        /// <param name="points">The points the multi points will be composed of.</param>
        public MultiPoint2(IEnumerable<Point2> points)
            : base(null == points ? new List<Point2>() : new List<Point2>(points)) { }

        /// <summary>
        /// Calculates the distance between this multi point and the point, <paramref name="p"/>
        /// </summary>
        /// <param name="p">The point to calculate distance to.</param>
        /// <returns>The distance.</returns>
        public double Distance(Point2 p)
        {
            return System.Math.Sqrt(DistanceSquared(p));
        }
        /// <summary>
        /// Calculates the distance between this multi point and the point, <paramref name="p"/>
        /// </summary>
        /// <param name="p">The point to calculate distance to.</param>
        /// <returns>The distance.</returns>
        public double Distance(IPoint2<double> p)
        {
            return Distance(new Point2(p));
        }
        /// <summary>
        /// Calculates the squared distance between this multi point and the point, <paramref name="p"/>
        /// </summary>
        /// <param name="p">The point to calculate squared distance to.</param>
        /// <returns>The squared distance.</returns>
        public double DistanceSquared(Point2 p)
        {
            if (Count > 0)
            {
                double d = this[0].DistanceSquared(p);
                for (int i = 1; i < Count; i++)
                {
                    d = System.Math.Min(d, this[i].DistanceSquared(p));
                }
                return d;
            }
            return Double.NaN;
        }
        /// <summary>
        /// Calculates the squared distance between this multi point and the point, <paramref name="p"/>
        /// </summary>
        /// <param name="p">The point to calculate squared distance to.</param>
        /// <returns>The squared distance.</returns>
        public double DistanceSquared(IPoint2<double> p)
        {
            return DistanceSquared(new Point2(p));
        }
        /// <summary>
        /// Determines if a point intersects this multi point.
        /// </summary>
        /// <param name="p">A point to test intersection with.</param>
        /// <returns>True when a point intersects this multi point.</returns>
        public bool Intersects(Point2 p)
        {
            for (int i = 0; i < Count; i++)
            {
                if (this[i].Equals(p))
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// Determines if a point intersects this multi point.
        /// </summary>
        /// <param name="p">A point to test intersection with.</param>
        /// <returns>True when a point intersects this multi point.</returns>
        public bool Intersects(IPoint2<double> p)
        {
            return Intersects(new Point2(p));
        }
        /// <summary>
        /// Calculates a minimum bounding rectangle for this multi point.
        /// </summary>
        /// <returns>A minimum bounding rectangle.</returns>
        public Mbr GetMbr()
        {
            if (Count > 1)
            {
                Mbr result = new Mbr(this[0], this[1]);
                for (int i = 2; i < Count; i++)
                {
                    result = result.Union(this[i]);
                }
                return result;
            }
            return (1 == Count) ? new Mbr(this[0]) : Mbr.Invalid;
        }
        IMbr<double> IHasMbr<double>.GetMbr()
        {
            return GetMbr();
        }
        /// <summary>
        /// Calculates the centroid.
        /// </summary>
        /// <returns>A centroid.</returns>
        public Point2 GetCentroid()
        {
            if (0 == Count)
            {
                return Point2.Invalid;
            }
            if (1 == Count)
            {
                return this[0];
            }
            double xsum = this[0].X;
            double ysum = this[0].Y;
            for (int i = 1; i < Count; i++)
            {
                xsum += this[i].X;
                ysum += this[i].Y;
            }
            double c = Count;
            return new Point2(xsum / c, ysum / c);
        }
        IPoint2<double> IHasPlanarCentroid<double>.GetCentroid()
        {
            return GetCentroid();
        }

        



        /// <summary>
        /// Creates an identical multi points.
        /// </summary>
        /// <returns>A multi point.</returns>
        public MultiPoint2 Clone()
        {
            return new MultiPoint2(this);
        }
        object ICloneable.Clone()
        {
            return Clone();
        }

        /// <summary>
        /// Indicates whether the current object is equal to another object of the same type.
        /// </summary>
        /// <returns>
        /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
        /// </returns>
        /// <param name="other">An object to compare with this object.</param>
        public bool Equals(MultiPoint2 other)
        {
            if (ReferenceEquals(this, other))
            {
                return true;
            }
            if (ReferenceEquals(null, other))
            {
                return false;
            }
            if (Count == other.Count)
            {
                for (int i = 0; i < Count; i++)
                {
                    if (!this[i].Equals(other[i]))
                    {
                        return false;
                    }
                }
                return true;
            }
            return false;
        }

        public override bool Equals(object obj)
        {
            return null != obj
                && (
                    (obj is MultiPoint2 && Equals(obj as MultiPoint2))
                )
            ;
        }

        public override int GetHashCode()
        {
            return GetMbr().GetHashCode() ^ 732903982;
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder(String.Concat("MultiPoint, ", Count, "point"));
            if (1 != Count)
            {
                sb.Append('s');
            }
            if (Count < 4)
            {
                for (int i = 0; i < Count; i++)
                {
                    sb.Append(' ');
                    sb.Append(this[i].ToString());
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// Determines if the given MBR contains this multi point.
        /// </summary>
        /// <param name="mbr">The MBR to test.</param>
        /// <returns>True if this multi point is within the given MBR.</returns>
        public bool Within(Mbr mbr)
        {
            return GetMbr().Within(mbr);
        }
        /// <summary>
        /// Determines if the given MBR contains this multi point.
        /// </summary>
        /// <param name="mbr">The MBR to test.</param>
        /// <returns>True if this multi point is within the given MBR.</returns>
        public bool Within(IMbr<double> mbr)
        {
            return GetMbr().Within(mbr);
        }

        /// <summary>
        /// Determines if this multi point is self-intersecting.
        /// </summary>
        /// <returns>True if self intersecting.</returns>
        /// <remarks>
        /// A multi point is considered self-intersecting if any two points have the same coordinates.
        /// </remarks>
        public bool IsSelfIntersecting()
        {
            for(int i = 0; i < Count ; i++)
            {
                for(int j = i + 1; j < Count; j++)
                {
                    if(this[i].Equals(this[j]))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
    }
}
